package com.flowable.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.flowable.common.result.CommonResult;
import com.flowable.service.GroupService;
import org.flowable.engine.IdentityService;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 组 实现
 */
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private IdentityService identityService;

    /**
     * 添加或修改 组
     *
     * @param id
     * @param name
     * @param type
     * @param version
     */
    @Override
    public CommonResult modifyGroup(String id, String name, String type, int version) {
        // 先查询
        GroupEntityImpl queryGroup = (GroupEntityImpl) identityService.createGroupQuery().groupId(id).singleResult();
        GroupEntityImpl newGroup = new GroupEntityImpl();
        if (queryGroup == null) {
            newGroup.setId(id);
            // 新增：revision = 0 表示这是一个新添加的组
            newGroup.setRevision(0);
        } else {
            // 修改：revision会自动递增
            newGroup = queryGroup;
        }
        newGroup.setName(name);
        newGroup.setType(type);
        JSONObject jsonObject = new JSONObject();
        try {
            identityService.saveGroup(newGroup);
        } catch (Exception e) {
            CommonResult.failed(e.getMessage());
        }
        jsonObject.put("groupId", newGroup.getId());
        jsonObject.put("groupName", newGroup.getName());
        jsonObject.put("groupType", newGroup.getType());
        jsonObject.put("groupRevision", newGroup.getRevision());
        return CommonResult.success(jsonObject);
    }

}
